<template>
    <div class="product-page">
        <el-row :gutter="20">
            <!-- 商品图片 -->
            <el-col :span="12">
                <el-card class="product-image-card">
                    <el-image :src="product.image" fit="cover" class="product-image" />
                    <div class="image-list">
                        <el-image
                            v-for="(image, index) in product.images"
                            :key="index"
                            :src="image"
                            fit="cover"
                            class="thumbnail"
                            @click="product.image = image"
                        />
                    </div>
                </el-card>
            </el-col>

            <!-- 商品信息 -->
            <el-col :span="12">
                <el-card class="product-info-card">
                    <h1 class="product-name">{{ product.name }}</h1>
                    <div class="price-section">
                        <span class="price">¥{{ product.price }}</span>
                        <span class="original-price" v-if="product.originalPrice">¥{{ product.originalPrice }}</span>
                    </div>
                    <div class="product-meta">
                        <span class="school">{{ product.school }}</span>
                        <span class="category">{{ product.category }}</span>
                        <span class="time">{{ product.time }}</span>
                    </div>
                    <div class="description">
                        <h3>商品描述</h3>
                        <p>{{ product.description }}</p>
                    </div>
                    <div class="condition">
                        <h3>商品成色</h3>
                        <p>{{ product.condition }}</p>
                    </div>
                    <div class="actions">
                        <el-button type="primary" size="large" @click="handleContact">联系卖家</el-button>
                        <el-button type="success" size="large" @click="handleAddToCart">加入购物车</el-button>
                    </div>
                </el-card>

                <!-- 卖家信息 -->
                <el-card class="seller-card">
                    <div class="seller-info">
                        <el-avatar :size="50" :src="product.seller.avatar" />
                        <div class="seller-details">
                            <h3>{{ product.seller.name }}</h3>
                            <p class="seller-stats">
                                <span>已售 {{ product.seller.soldCount }}</span>
                                <span>好评率 {{ product.seller.rating }}%</span>
                            </p>
                        </div>
                    </div>
                    <div class="seller-actions">
                        <el-button type="primary" plain @click="handleViewSeller">查看主页</el-button>
                        <el-button type="success" plain @click="handleFollow">关注</el-button>
                    </div>
                </el-card>
            </el-col>
        </el-row>

        <!-- 商品详情 -->
        <el-card class="detail-card">
            <template #header>
                <div class="card-header">
                    <h3>商品详情</h3>
                </div>
            </template>
            <div class="detail-content">
                <div v-for="(detail, index) in product.details" :key="index" class="detail-item">
                    <h4>{{ detail.title }}</h4>
                    <p>{{ detail.content }}</p>
                </div>
            </div>
        </el-card>

        <!-- 相关推荐 -->
        <el-card class="related-card">
            <template #header>
                <div class="card-header">
                    <h3>相关推荐</h3>
                </div>
            </template>
            <el-row :gutter="20">
                <el-col :span="6" v-for="item in relatedProducts" :key="item.id">
                    <el-card class="related-product" @click="goToProduct(item)">
                        <el-image :src="item.image" fit="cover" class="related-image" />
                        <div class="related-info">
                            <h4>{{ item.name }}</h4>
                            <p class="price">¥{{ item.price }}</p>
                        </div>
                    </el-card>
                </el-col>
            </el-row>
        </el-card>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { createConversation } from '../../api/chat'

const route = useRoute()
const router = useRouter()

// 商品数据
const product = ref({
    id: 1,
    name: '高等数学教材',
    price: 30,
    originalPrice: 50,
    description: '九成新，无笔记，适合大一新生使用。',
    condition: '九成新',
    image: 'https://picsum.photos/800/800?random=1',
    images: [
        'https://picsum.photos/800/800?random=1',
        'https://picsum.photos/800/800?random=2',
        'https://picsum.photos/800/800?random=3',
        'https://picsum.photos/800/800?random=4'
    ],
    school: '北京大学',
    category: '教材教辅',
    time: '1小时前',
    details: [
        {
            title: '基本信息',
            content: '作者：同济大学数学系\n出版社：高等教育出版社\n版次：第七版\n出版时间：2018年'
        },
        {
            title: '使用说明',
            content: '教材保存完好，无破损，无笔记，适合大一新生使用。'
        },
        {
            title: '交易说明',
            content: '支持当面交易，地点：北京大学校内\n也可以选择快递，邮费自理。'
        }
    ],
    seller: {
        id: 1,
        name: '张三',
        avatar: 'https://picsum.photos/100/100?random=1',
        soldCount: 56,
        rating: 98
    }
})

// 相关推荐
const relatedProducts = ref([
    {
        id: 2,
        name: '线性代数教材',
        price: 25,
        image: 'https://picsum.photos/200/200?random=5'
    },
    {
        id: 3,
        name: '大学物理教材',
        price: 35,
        image: 'https://picsum.photos/200/200?random=6'
    },
    {
        id: 4,
        name: 'C语言程序设计',
        price: 20,
        image: 'https://picsum.photos/200/200?random=7'
    },
    {
        id: 5,
        name: '英语四级词汇',
        price: 15,
        image: 'https://picsum.photos/200/200?random=8'
    }
])

// 方法
const handleContact = async () => {
    try {
        // 检查用户登录状态
        const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
        const userId = userInfo.id

        if (!userId) {
            ElMessage.error('请先登录才能联系卖家')
            return
        }

        if (!product.value?.seller?.id) {
            ElMessage.error('无法获取卖家信息')
            return
        }

        // 创建会话
        const response = await createConversation({
            userId: userId,
            partnerId: product.value.seller.id
        })

        // 根据后端返回的错误码来判断
        if (!response) {
            ElMessage.error('网络异常，请稍后重试')
            return
        }
        
        // 只有当code为200时才视为成功
        if (response.code !== 200) {
            // 根据不同错误码显示不同错误信息
            switch (response.code) {
                case 400:
                    ElMessage.error(response.message || '请求参数错误')
                    break
                case 401:
                    ElMessage.error('用户未登录或登录已过期')
                    break
                case 403:
                    ElMessage.error('您没有权限联系该卖家')
                    break
                case 404:
                    ElMessage.error('卖家信息不存在')
                    break
                case 500:
                    ElMessage.error('服务器内部错误，请稍后重试')
                    break
                default:
                    // 始终优先使用后端返回的错误信息
                    ElMessage.error(response.message || `创建会话失败(${response.code})`)
            }
            // 无论什么错误都不跳转
            return
        }

        // 只有成功时才显示消息并跳转
        ElMessage.success('已成功发起对话')
        
        router.push({
            path: '/chat',
            query: {
                sellerId: product.value.seller.id,
                productId: product.value.id
            }
        })
    } catch (error) {
        console.error('联系卖家出错:', error)
        ElMessage.error('联系卖家失败，请稍后重试')
    }
}

const handleAddToCart = () => {
    ElMessage.success('已加入购物车')
}

const handleViewSeller = () => {
    router.push(`/user/${product.value.seller.id}`)
}

const handleFollow = () => {
    ElMessage.success('关注成功')
}

const goToProduct = (product: any) => {
    router.push({
        path: '/product',
        query: { id: product.id }
    })
}

onMounted(() => {
    // 从路由参数获取商品ID
    const productId = route.query.id
    // TODO: 根据ID加载商品数据
})
</script>

<style scoped>
.product-page {
    padding: 20px;
}

.product-image-card {
    margin-bottom: 20px;
}

.product-image {
    width: 100%;
    height: 400px;
    border-radius: 4px;
}

.image-list {
    display: flex;
    gap: 10px;
    margin-top: 10px;
}

.thumbnail {
    width: 80px;
    height: 80px;
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.3s;
}

.thumbnail:hover {
    transform: scale(1.05);
}

.product-info-card {
    margin-bottom: 20px;
}

.product-name {
    margin: 0 0 20px;
    font-size: 24px;
    color: #333;
}

.price-section {
    margin-bottom: 20px;
}

.price {
    font-size: 28px;
    color: #f56c6c;
    font-weight: 600;
    margin-right: 10px;
}

.original-price {
    font-size: 16px;
    color: #999;
    text-decoration: line-through;
}

.product-meta {
    display: flex;
    gap: 20px;
    color: #666;
    margin-bottom: 20px;
}

.description, .condition {
    margin-bottom: 20px;
}

.description h3, .condition h3 {
    font-size: 16px;
    color: #333;
    margin-bottom: 10px;
}

.description p, .condition p {
    color: #666;
    line-height: 1.6;
    white-space: pre-line;
}

.actions {
    display: flex;
    gap: 10px;
}

.seller-card {
    margin-bottom: 20px;
}

.seller-info {
    display: flex;
    align-items: center;
    gap: 15px;
    margin-bottom: 15px;
}

.seller-details h3 {
    margin: 0 0 5px;
    font-size: 16px;
    color: #333;
}

.seller-stats {
    display: flex;
    gap: 15px;
    color: #666;
    font-size: 14px;
}

.seller-actions {
    display: flex;
    gap: 10px;
}

.detail-card {
    margin-bottom: 20px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.card-header h3 {
    margin: 0;
    font-size: 18px;
    color: #333;
}

.detail-content {
    padding: 20px 0;
}

.detail-item {
    margin-bottom: 20px;
}

.detail-item h4 {
    font-size: 16px;
    color: #333;
    margin-bottom: 10px;
}

.detail-item p {
    color: #666;
    line-height: 1.6;
    white-space: pre-line;
}

.related-card {
    margin-bottom: 20px;
}

.related-product {
    cursor: pointer;
    transition: all 0.3s;
}

.related-product:hover {
    transform: translateY(-5px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.related-image {
    width: 100%;
    height: 150px;
    border-radius: 4px;
}

.related-info {
    padding: 10px 0;
}

.related-info h4 {
    margin: 0 0 8px;
    font-size: 14px;
    color: #333;
}

.related-info .price {
    color: #f56c6c;
    font-size: 16px;
    font-weight: 600;
    margin: 0;
}
</style> 